package com.qny.ai.controller;

import com.qny.ai.common.ApiResponse;
import com.qny.ai.service.impl.QiniuVoiceService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/voice")
@RequiredArgsConstructor
public class VoiceController {
    
    private final QiniuVoiceService qiniuVoiceService;
    
    /**
     * 获取音色列表
     */
    @GetMapping("/list")
    public ApiResponse<Object> getVoiceList() {
        try {
            String voiceListJson = qiniuVoiceService.getVoiceList();
            // 解析JSON字符串为对象
            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
            com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(voiceListJson);
            
            // 检查是否有data字段，如果有则提取data字段的内容
            if (rootNode.has("data")) {
                Object voiceList = mapper.treeToValue(rootNode.get("data"), Object.class);
                return ApiResponse.ok(voiceList);
            } else {
                // 如果没有data字段，直接返回整个响应
                Object voiceList = mapper.readValue(voiceListJson, Object.class);
                return ApiResponse.ok(voiceList);
            }
        } catch (Exception e) {
            return ApiResponse.fail(500, "获取音色列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 音色试听
     */
    @PostMapping("/preview")
    public ApiResponse<String> previewVoice(@RequestBody Map<String, String> request) {
        try {
            String voiceType = request.get("voiceType");
            
            if (voiceType == null || voiceType.trim().isEmpty()) {
                return ApiResponse.fail(400, "音色类型不能为空");
            }
            
            // 使用固定文本进行TTS
            String fixedText = "你好，这是音色试听，欢迎使用我们的语音服务。";
            String audioBase64 = qiniuVoiceService.ttsToBase64(fixedText, voiceType, "wav");
            if (audioBase64 == null || audioBase64.isEmpty()) {
                return ApiResponse.fail(500, "音色试听生成失败");
            }
            
            return ApiResponse.ok(audioBase64);
        } catch (Exception e) {
            return ApiResponse.fail(500, "音色试听失败: " + e.getMessage());
        }
    }
}
